<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ewaypayment {
    var $myGatewayURL;
    var $myCustomerID;
    var $myTransactionData = array();
    var $myCurlPreferences = array();

    //Class Constructor
	function Ewaypayment($params = NULL) {
		$customerID = EWAY_DEFAULT_CUSTOMER_ID;
		$method = EWAY_DEFAULT_PAYMENT_METHOD;
		$liveGateway  = EWAY_DEFAULT_LIVE_GATEWAY;
		if(is_array($params))
		{			
			list($customerID, $method, $liveGateway) = $params;
		}
		$this->myCustomerID = $customerID;
	    switch($method){

		    case REAL_TIME;

		    		if($liveGateway)
		    			$this->myGatewayURL = EWAY_PAYMENT_LIVE_REAL_TIME;
		    		else
	    				$this->myGatewayURL = EWAY_PAYMENT_LIVE_REAL_TIME_TESTING_MODE;
	    		break;
	    	 case REAL_TIME_CVN;
		    		if($liveGateway)
		    			$this->myGatewayURL = EWAY_PAYMENT_LIVE_REAL_TIME_CVN;
		    		else
	    				$this->myGatewayURL = EWAY_PAYMENT_LIVE_REAL_TIME_CVN_TESTING_MODE;
	    		break;
	    	case GEO_IP_ANTI_FRAUD;
		    		if($liveGateway)
		    			$this->myGatewayURL = EWAY_PAYMENT_LIVE_GEO_IP_ANTI_FRAUD;
		    		else
		    			//in testing mode process with REAL-TIME
	    				$this->myGatewayURL = EWAY_PAYMENT_LIVE_GEO_IP_ANTI_FRAUD_TESTING_MODE;
	    		break;
    	}
	}
	
	
	//Payment Function
	function doPayment() {
		$xmlRequest = "<ewaygateway><ewayCustomerID>" . $this->myCustomerID . "</ewayCustomerID>";
		foreach($this->myTransactionData as $key=>$value)
			$xmlRequest .= "<$key>$value</$key>";
        $xmlRequest .= "</ewaygateway>";
		 
		$xmlResponse = $this->sendTransactionToEway($xmlRequest);

		if($xmlResponse!=""){			
			$responseFields = $this->parseResponse($xmlResponse);
			return $responseFields;
		}else{
            $responseFields["EWAYTRXNSTATUS"]="False";
            $responseFields["EWAYTRXNERROR"]="Payment Gateway could not be reach.";
            return $responseFields;
        };
	}

	//Send XML Transaction Data and receive XML response
	function sendTransactionToEway($xmlRequest) {		
		$ch = curl_init($this->myGatewayURL);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        foreach($this->myCurlPreferences as $key=>$value)
        	curl_setopt($ch, $key, $value);

        $xmlResponse = curl_exec($ch);		
        if(curl_errno( $ch ) == CURLE_OK)
        	return $xmlResponse;
	}
	
	
	//Parse XML response from eway and place them into an array
	function parseResponse($xmlResponse){
		$xml_parser = xml_parser_create();
		xml_parse_into_struct($xml_parser,  $xmlResponse, $xmlData, $index);
        $responseFields = array();
        foreach($xmlData as $data)
	    	if($data["level"] == 2)
	    		if(isset($data['value']))
        			$responseFields[$data["tag"]] = $data["value"];
        return $responseFields;
	}
	
	
	//Set Transaction Data
	//Possible fields: "TotalAmount", "CustomerFirstName", "CustomerLastName", "CustomerEmail", "CustomerAddress", "CustomerPostcode", "CustomerInvoiceDescription", "CustomerInvoiceRef",
	//"CardHoldersName", "CardNumber", "CardExpiryMonth", "CardExpiryYear", "TrxnNumber", "Option1", "Option2", "Option3", "CVN", "CustomerIPAddress", "CustomerBillingCountry"
	function setTransactionData($field, $value) {
		if($field=="TotalAmount")
			$value = round($value*100);
		$this->myTransactionData["eway" . $field] = htmlentities(trim($value));
	}
	
	
	//receive special preferences for Curl
	function setCurlPreferences($field, $value) {
		$this->myCurlPreferences[$field] = $value;
	}
		
	
	//obtain visitor IP even if is under a proxy
	function getVisitorIP(){
		$ip = $_SERVER["REMOTE_ADDR"];
		if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
			$proxy = $_SERVER["HTTP_X_FORWARDED_FOR"];
			if(ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$proxy))
			        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		return $ip;
	}
	
	
	function pay_all($total_amount, $firstname, $lastname, $email, $address, $postcode, $description, $invoice_ref, $card_name, $card_num, $card_moth, $card_year, $trans_number){
		
		$this->setTransactionData("TotalAmount", $total_amount); //mandatory field
		$this->setTransactionData("CustomerFirstName", $firstname);
		$this->setTransactionData("CustomerLastName", $lastname);
		$this->setTransactionData("CustomerEmail", $email);
		$this->setTransactionData("CustomerAddress", $address);
		$this->setTransactionData("CustomerPostcode", $postcode);
		$this->setTransactionData("CustomerInvoiceDescription", $description);
		$this->setTransactionData("CustomerInvoiceRef", $invoice_ref);
		$this->setTransactionData("CardHoldersName", $card_name); //mandatory field
		$this->setTransactionData("CardNumber", $card_num); //mandatory field
		$this->setTransactionData("CardExpiryMonth", $card_moth); //mandatory field
		$this->setTransactionData("CardExpiryYear", $card_year); //mandatory field
		$this->setTransactionData("TrxnNumber", $trans_number);
		$this->setTransactionData("Option1", "");
		$this->setTransactionData("Option2", "");
		$this->setTransactionData("Option3", "");		
		
		//for REAL_TIME_CVN
		$this->setTransactionData("CVN", "123");

		//for GEO_IP_ANTI_FRAUD
		$this->setTransactionData("CustomerIPAddress", $this->getVisitorIP()); //mandatory field when using Geo-IP Anti-Fraud
		$this->setTransactionData("CustomerBillingCountry", "AU"); //mandatory field when using Geo-IP Anti-Fraud
		
		
		
		$this->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0);  		
		$thisResponseFields = $this->doPayment();
		if($thisResponseFields["EWAYTRXNSTATUS"]=="False"){
			/*
			print "Transaction Error: " . $thisResponseFields["EWAYTRXNERROR"] . "<br>\n";		
			foreach($thisResponseFields as $key => $value)
				print "\n<br>\$thisResponseFields[\"$key\"] = $value";
			*/
			$err_msg = $thisResponseFields["EWAYTRXNERROR"];
			//list($err, $msg) = split(':', $err_msg);
			return $err_msg;
					
		}else if($thisResponseFields["EWAYTRXNSTATUS"]=="True"){
			/*			
			print "Transaction Success: " . $thisResponseFields["EWAYTRXNERROR"]  . "<br>\n";
			foreach($thisResponseFields as $key => $value)
				print "\n<br>\$thisResponseFields[\"$key\"] = $value";
			*/
			return true;
		}
	}
}
?>